package com.aqie.easy.string;

/**
 * 415 字符串相加 todo
 */
public class AddStrings {
    /**
     * 1. 8ms
     * @param num1
     * @param num2
     * @return
     */
    public String addStrings(String num1, String num2) {
        StringBuilder str = new StringBuilder();
        int i = num1.length()-1;
        int j = num2.length()-1;
        int carry = 0;
        while(i>=0 && j>=0) {
            int res = num1.charAt(i)-'0' + num2.charAt(j)-'0' + carry;
            if(res>=10) carry = 1;
            else carry = 0;
            res = res%10;
            str.append(res);
            i--;
            j--;
        }
        while(j>=0) {
            int res = num2.charAt(j)-'0' + carry;
            if(res>=10) carry = 1;
            else carry = 0;
            res = res%10;
            str.append( res );
            j--;
        }
        while(i>=0) {
            int res = num1.charAt(i)-'0' + carry;
            if(res>=10) carry = 1;
            else carry = 0;
            res = res%10;
            str.append( res );
            i--;
        }
        if(carry == 1) str.append("1");
        return  str.reverse().toString();
    }

    /**
     * 2. 6ms
     * @param num1
     * @param num2
     * @return
     */
    public String addStrings2(String num1, String num2) {
        StringBuilder res = new StringBuilder("");
        int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
        while(i >= 0 || j >= 0){
            int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
            int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
            int tmp = n1 + n2 + carry;
            carry = tmp / 10;
            res.append(tmp % 10);
            i--; j--;
        }
        if(carry == 1) res.append(1);
        return res.reverse().toString();
    }



}
